package com.xof.phonecall.extipetrpide

import android.Manifest
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.xof.phonecall.MyApplication
import com.xof.phonecall.valipetrpide.ValGlobalConstant
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.*

fun Context.getAndroid(): String {
    val androidID = Settings.System.getString(contentResolver, Settings.Secure.ANDROID_ID)
    if (androidID.isBlank())
        return System.currentTimeMillis().toString()

    if (androidID.contains("00000000"))
        return System.currentTimeMillis().toString()

    return androidID
}

@SuppressLint("SimpleDateFormat")
fun Context.getDateStringAfterDays(dayExt: Int?): String {
    dayExt?.let {
        val cal = Calendar.getInstance()
        cal.add(Calendar.DAY_OF_MONTH, it)
        val f1 = SimpleDateFormat("yyyy-MM-dd")
        val s2 = f1.format(cal.time)
        return s2
    }
    return ""
}

fun Context.openSystemCall(phone: String?) {
    val intent = Intent(Intent.ACTION_DIAL)
    phone?.let {
        val tempTel = Uri.encode(it)
        val data = Uri.parse("tel:$tempTel")
        intent.data = data
    }
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    startActivity(intent)
}

@SuppressLint("QueryPermissionsNeeded")
fun Context.openUrlFromSysBrowser(url: String?) {
    url?.let {
        val uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        if (intent.resolveActivity(packageManager) != null) {
            startActivity(intent)
        } else {
            startActivity(Intent.createChooser(intent, "Please select a browser to open"))
        }
    }
}

@SuppressLint("QueryPermissionsNeeded")
fun Context.startSystemBrowser(url: String?) {
    url?.let {
        val uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        if (intent.resolveActivity(packageManager) != null) {
            startActivity(intent)
        } else {
            startActivity(Intent.createChooser(intent, "Please select a browser to open"))
        }
    }
}

fun Context.copyToClipboard(content: String) {
    val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clipData = ClipData.newPlainText("Label", content)
    clipboardManager.setPrimaryClip(clipData)
    Toast.makeText(this, "Copy Success", Toast.LENGTH_SHORT).show()
}

fun Context.isAgreeLaunchPermissions(): Boolean {
    try {
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_CONTACTS
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: READ_CONTACTS")
            return false
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: CAMERA")
            return false
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: ACCESS_COARSE_LOCATION")
            return false
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: ACCESS_FINE_LOCATION")
            return false
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: WRITE_EXTERNAL_STORAGE")
            return false
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: READ_EXTERNAL_STORAGE")
            return false
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_SMS
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: READ_SMS")
            return false
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_PHONE_STATE
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: READ_PHONE_STATE")
            return false
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_CALENDAR
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: READ_CALENDAR")
            return false
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.GET_ACCOUNTS
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: GET_ACCOUNTS")
            return false
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            return PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_MEDIA_LOCATION
            )
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return true
}

fun Context.getNotAgreeLaunchPermissions(): List<String> {
    val list = mutableListOf<String>()
    try {
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_CONTACTS
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: READ_CONTACTS")
            list.add(Manifest.permission.READ_CONTACTS)
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: CAMERA")
            list.add(Manifest.permission.CAMERA)
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: ACCESS_COARSE_LOCATION")
            list.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: ACCESS_FINE_LOCATION")
            list.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: WRITE_EXTERNAL_STORAGE")
            list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: READ_EXTERNAL_STORAGE")
            list.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_SMS
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: READ_SMS")
            list.add(Manifest.permission.READ_SMS)
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_PHONE_STATE
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: READ_PHONE_STATE")
            list.add(Manifest.permission.READ_PHONE_STATE)
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_CALENDAR
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: READ_CALENDAR")
            list.add(Manifest.permission.READ_CALENDAR)
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.GET_ACCOUNTS
            )
        ) {
            Log.d(this::class.java.simpleName, "checkPermissions: GET_ACCOUNTS")
            list.add(Manifest.permission.GET_ACCOUNTS)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_MEDIA_LOCATION
                )
            ) {
                Log.d(this::class.java.simpleName, "checkPermissions: ACCESS_MEDIA_LOCATION")
                list.add(Manifest.permission.ACCESS_MEDIA_LOCATION)
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return list
}

fun Context.getInAppDirectory(): String {
    val inAppDir = "${
        MyApplication.context.applicationContext.filesDir
    }${File.separator}${ValGlobalConstant.VAL_PRODUCT}Images"

    val dirFile = File(inAppDir)
    if (!dirFile.exists()) {
        dirFile.mkdirs()
    }

    return inAppDir
}

fun Context.getInAppImageFilePath(): String {
    val pictureId = System.currentTimeMillis().toString() + ""
    val imgDir = getInAppDirectory()
    return "$imgDir/$pictureId.jpg"
}


fun Context.getCacheDirectory(): String {
    val inAppDir = "${
        MyApplication.context.applicationContext.filesDir
    }${File.separator}${ValGlobalConstant.VAL_PRODUCT}Images"

    val dirFile = File(inAppDir)
    if (!dirFile.exists()) {
        dirFile.mkdirs()
    }

    return inAppDir
}

fun Context.getCacheImageFilePath(): String {
    val pictureId = System.currentTimeMillis().toString() + ""
    val imgDir = getCacheDirectory()
    return "$imgDir/$pictureId.jpg"
}

fun Context.getCacheImageFilePath(extName: String): String {
    val pictureId = extName + System.currentTimeMillis().toString() + ""
    val imgDir = getCacheDirectory()
    return "$imgDir/$pictureId.jpg"
}

fun Context.saveAblumFileFromURI(contentURI: Uri): String {
    try {
        println(contentURI.path)
        val imgDir: String = getCacheDirectory()
        val pictureId = System.currentTimeMillis().toString()
        val outFilePath = "$imgDir/$pictureId.jpg"
        val imgInputStream: InputStream =
            contentResolver.openInputStream(contentURI) ?: return ""
        val outFile = File(outFilePath)
        val buffer = ByteArray(1024)
        var len: Int
        val fos = FileOutputStream(outFile)
        while (imgInputStream.read(buffer).also { len = it } != -1) {
            fos.write(buffer, 0, len)
        }
        fos.flush()
        fos.close()
        imgInputStream.close()
        return outFilePath
    } catch (e: IOException) {
        e.printStackTrace()
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return ""
}

